import * as fs from 'node:fs'
import { join } from 'node:path'
import { ClassSerializerInterceptor, RequestMethod } from '@nestjs/common'
import { NestFactory, PartialGraphHost, Reflector } from '@nestjs/core'
import { NestExpressApplication } from '@nestjs/platform-express'
import * as session from 'express-session'
// import { ExceptionsFilter } from '@/filters/exceptions.filter';
import { contentMiddleware } from '@/common/middleware/content.middleware'
import { setupSwagger } from '@/common/swagger'
import { AppModule } from './app.module'

const PREFIX = 'douxian'

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    abortOnError: false, // 服务错误时不退出
  })

  // 全局前缀
  app.setGlobalPrefix(PREFIX, {
    exclude: [{ path: '/', method: RequestMethod.GET }],
  })

  app.useStaticAssets(join(process.cwd(), 'uploads'), {
    prefix: '/static',
  })
  app.use(contentMiddleware)
  // 开启使用@Expose()输出实体的 get 属性
  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))
  // 放开请求体大小限制
  app.useBodyParser('json', { limit: '10mb' })
  app.useBodyParser('urlencoded', { limit: '10mb', extended: true })

  app.use(
    session({
      secret: process.env.JWT_SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: { maxAge: 60 * 60 * 1000 }, // 1小时
    }),
  )

  setupSwagger(app)

  const port = process.env.SERVE_PORT

  await app.listen(port)
  console.log(`🚀 Service: \x1B[34mhttp://127.0.0.1:${port}\x1B[0m`)
  console.log(`📄 Swagger Docs: http://127.0.0.1:${port}/api-docs`)
  console.log(`📄 Swagger Json: http://127.0.0.1:${port}/api-docs/json`)
}

bootstrap().catch(() => {
  fs.writeFileSync('graph.json', PartialGraphHost.toString() ?? '')
  process.exit(1)
})
